#include "flash_if.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Unlocks Flash for write access
  * @param  None
  * @retval None
  */
void FLASH_If_Init(void)
{
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
}

/**
  * @brief  This function does an erase of all user flash area
  * @param  StartSector: start of user flash area
  * @retval 0: user flash area successfully erased
  *         1: error occurred
  */
int8_t FLASH_If_Erase(uint32_t StartSector)
{
    if(StartSector < MM32_FLASH_BASE || StartSector % 4)return 1;
    FLASH_ErasePage(StartSector);
    FLASH_ClearFlag(FLASH_FLAG_EOP );
    return 0;
}
/**
  * @brief  This function writes a data buffer in flash (data are 32-bit aligned).
  * @note   After writing data buffer, the flash content is checked.
  * @param  FlashAddress: start address for writing data buffer
  * @param  Data: pointer on data buffer
  * @param  DataLength: length of data buffer (unit is 32-bit word)
  * @retval 0: Data successfully written to Flash memory
  *         1: Error occurred while writing data in Flash memory
  *         2: Written Data in flash memory is different from expected one
  */
uint32_t FLASH_If_Write(__IO uint32_t* FlashAddress, uint32_t* Data, uint16_t DataLength)
{
    uint32_t i = 0;
    for (i = 0; (i < DataLength) && (*FlashAddress <= (USER_FLASH_END_ADDRESS - 4)); i++) {
        if (FLASH_ProgramWord(*FlashAddress,  *(uint32_t*)(Data + i)) != FLASH_COMPLETE)
            break;
        *FlashAddress += 4;
    }
    return 0;
}
/**
  * @brief  locks Flash for write access
  * @param  None
  * @retval None
  */
void FLASH_If_UnInit(void)
{
    FLASH_ClearFlag(FLASH_FLAG_EOP );
    FLASH_Lock();
}
